package leetcode.stack;


import java.util.*;

/**
 * 20. 有效的括号
 *
 *
 * Stack类的基本使用
 *      peek() 查看栈顶元素
 *      push() 元素压入栈顶
 *      pop()  取出栈顶元素
 *      isEmpty() 判断栈是否为空
 *
 *
 */
public class IsValid {

    public static void main(String[] args) {
        IsValid solution = new IsValid();
        boolean res = solution.isValid("){");
        System.out.println(res);
    }


    /**
     * 左右括号进行匹配  (自己写的)
     *
     * @param s 字符串
     * @return true or false
     */
    public boolean isValid0(String s) {
        char[] chars = s.toCharArray();
        int n = chars.length;
        if (n % 2 == 1) {
            return false;
        }
        Stack<Character> stack = new Stack<>();

        Map<Character, Character> map = new HashMap<>(4);
        map.put(']', '[');
        map.put(')', '(');
        map.put('}', '{');

        // 遍历数组
        for (char c : chars) {
            if (map.containsKey(c)) {
                if (stack.isEmpty() || map.get(c) != stack.peek()) {
                    return false;
                }
                stack.pop();
            } else {
                stack.push(c);
            }
        }
        return stack.empty();
    }


    /**
     * 左右括号进行匹配
     * 官方写法 使用 Deque接口的实现类 LinkedList完成栈的功能(代替Stack)
     *
     * @param s 字符串
     * @return true or false
     */
    public boolean isValid(String s) {
        int n = s.length();
        if (n % 2 == 1) {
            return false;
        }

        Map<Character, Character> pairs = new HashMap<Character, Character>() {{
            put(')', '(');
            put(']', '[');
            put('}', '{');
        }};
        Deque<Character> stack = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            char ch = s.charAt(i);
            if (pairs.containsKey(ch)) {
                if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
                    return false;
                }
                stack.pop();
            } else {
                stack.push(ch);
            }
        }
        return stack.isEmpty();
    }


}
